package cn.com.shaom.learning.sb.shiro.example.web;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * ClassName: LoginController
 * Description:
 * Date: 2018/2/22 10:54 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Controller
public class LoginController {

    @Resource
    FindByIndexNameSessionRepository<? extends ExpiringSession> sessionRepository;


    @RequestMapping("/findByUsername/{username}")
    @ResponseBody
    public Map findByUsername(@PathVariable(name = "username") String username) {
        Map<String, ? extends ExpiringSession> usersSessions = sessionRepository.findByIndexNameAndIndexValue(
                FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
        return usersSessions;
    }

    /**
     * 此方法不处理登录成功,由shiro进行处理
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, ModelMap modelMap) {

        String exception = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("exception=" + exception);

        //        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        //        SecurityUtils.getSubject().login(token);//登录


        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在：");
                msg = "UnknownAccountException -- > 账号不存在：";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                System.out.println("IncorrectCredentialsException -- > 密码不正确：");
                msg = "IncorrectCredentialsException -- > 密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> " + exception;
                System.out.println("else -- >" + exception);
            }
        }
        modelMap.addAttribute("msg", msg);
        return "/example/login";
    }
}
